/*
 * commons is a based project implemented
 * Copyright (C) 2024 Jasmine
 */
package com.easy.ip.utils;

import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 在线IP获取地址
 * <p>
 * 获取地址类 开放WebApi * 高德开放平台IP定位：https://lbs.amap.com/api/webservice/guide/api/ipconfig * 淘宝API： http://ip.taobao.com/ *
 * 淘宝API： http://ip.taobao.com/
 * </p>
 * 
 * @author Jasmine
 * @since 1.0.0
 */
public class IP2RegionOnLineUtils {
    static Logger log = LoggerFactory.getLogger(IP2RegionOnLineUtils.class);

    public static ObjectMapper objectMapper = new ObjectMapper();
    /**
     * IP地址查询
     */
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";

    /**
     * 未知地址
     */
    public static final String UNKNOWN = "XX XX";

    public static String getRealAddressByIP(String ip) {
        String address = UNKNOWN;
        // 内网不查询

        if (Objects.nonNull(ip) && IpUtil.internalIp(ip)) {
            return "内网IP";
        }
        // 可以在这里设置一个开关，是否远程查看ip所在地
        try {
            // TODO String rspStr = HttpUtil.createGet(IP_URL).body("ip=" + ip + "&json=true", "GBK").execute().body();
            String rspStr = "";
            if (StringUtils.isBlank(rspStr)) {
                log.error("获取地理位置异常 {}", ip);
                return UNKNOWN;
            }
            JsonNode jsonNode = objectMapper.readTree(rspStr);
            String pro = jsonNode.get("pro").asText();
            String proCode = jsonNode.get("proCode").asText();
            String city = jsonNode.get("city").asText();
            String cityCode = jsonNode.get("cityCode").asText();
            String region = jsonNode.get("region").asText();
            String regionCode = jsonNode.get("regionCode").asText();
            String regionNames = jsonNode.get("regionNames").asText();
            String addr = jsonNode.get("addr").asText();
            // return String.format("%s %s", region, city);
            return addr;
        } catch (Exception e) {
            log.error("获取地理位置异常 {}", e);
        }
        return address;
    }
}
